package com.kyzh.core.pager.weal.video

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.gushenge.atools.util.AView
import com.gushenge.atools.util.setMargins
import com.gushenge.core.beans.Video
import com.gushenge.core.requests.VideoRequest
import com.kyzh.core.R
import com.kyzh.core.adapters.VideoLikeAdapter
import com.kyzh.core.pager.weal.video.viewmodels.VideoLikeViewModel
import com.kyzh.core.utils.startGameDetailActivity
import kotlinx.android.synthetic.main.fragment_video_like.*
import org.jetbrains.anko.support.v4.dip


class VideoLikeFragment : Fragment() {


    private val beans = arrayListOf<Video>()
    private val adapter = VideoLikeAdapter(R.layout.item_video_attention,beans)
    private val viewModel by viewModels<VideoLikeViewModel>()
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_video_like, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()
    }

    private fun initView() {
        srlRoot.setMargins(dip(12.5f),AView.getStatusBarHeight(requireActivity())+dip(44),dip(12.5f),dip(12.5f))
        rvList.layoutManager = object:GridLayoutManager(requireActivity(),2){}
        rvList.adapter = adapter
        srlRoot.setOnRefreshListener {
            viewModel.refresh()
        }
        initData()
    }

    private fun initData() {
        viewModel.beans.observe(viewLifecycleOwner){
            if (viewModel.p==2){
                beans.clear()
            }
            beans.addAll(it)
            adapter.notifyDataSetChanged()
            srlRoot.isRefreshing=false
        }
        viewModel.getData()
        adapter.loadMoreModule.isEnableLoadMore=true
        adapter.loadMoreModule.isEnableLoadMoreIfNotFullPage=false
        adapter.loadMoreModule.setOnLoadMoreListener {
            viewModel.getData()
            adapter.loadMoreModule.loadMoreComplete()
        }

        adapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.ivQuxiao->{
                    VideoRequest.videoGuanzhu(VideoRequest.VideoAttention.QUGUAN,beans[position].id){
                        beans.removeAt(position)
                        adapter.notifyDataSetChanged()
                    }
                }
                R.id.tvDetail->{
                    startGameDetailActivity(beans[position].gid)
                }
            }
        }

    }

}